package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.adapter.PhotoAdapter;
import com.superfish.cutieshop.adapter.PhotoFolderAdapter;
import com.superfish.cutieshop.been.PhotoBean;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.SimpleAsync;
import com.superfish.cutieshop.utils.TimeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @author JackWu 相册
 */
@ContentView(R.layout.activity_photo)
public class PhotoActivity extends BaseActivity {

    private static final int TAKE_PICTURE = 0x120;

    public static void open(Activity act) {
        Intent i = new Intent(act, PhotoActivity.class);
        open(act, i);
    }

    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;


    @ViewInject(R.id.select_photo_gridview)
    private GridView select_photo_gridview;

    @ViewInject(R.id.select_photo_listview)
    private ListView select_photo_listview;
    @ViewInject(R.id.out_side_ll)
    private LinearLayout out_side_ll;
    private ContentResolver contentResolver;

    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashMap<String, Integer> tempDir = new HashMap<>();
    private List<PhotoBean> folderList = new ArrayList<>();
    private List<String> photoPathList = new ArrayList<>();
    private PhotoAdapter photoAdapter;
    private PhotoFolderAdapter folderAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mToolbar.setTitle("");
        setAppTitle("相册");
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        //动态设置颜色 根据当前星期时间设置
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        setSupportActionBar(mToolbar);
//        ImageLoader.getInstance().clearMemoryCache();
        init();
    }

    @Override
    protected void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what) {
            case BaseConfig.MessageCode.CROPER:
                this.finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_photo, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            openFolderChooser(false);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void init() {
        contentResolver = getContentResolver();
        // 执行异步加载
        new SimpleAsync(new SimpleAsync.SimpleCallback() {
            @Override
            public void onStart() {
                getSystemPhotoData();
            }

            @Override
            public void onPrepare() {
                showLoading();
            }

            @Override
            public void onFinish() {
                showContent();
                // 没有相片,直接添加一个只有调用相机的数据
                if (isEmptyList()) {
                    return;
                }
                photoPathList = folderList.get(0).imagePaths;
                photoAdapter = new PhotoAdapter(PhotoActivity.this,
                        photoPathList);
                // -- 倒叙一下

                folderAdapter = new PhotoFolderAdapter(
                        PhotoActivity.this, folderList);
                folderAdapter.setWhichFolder(0);
                LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) select_photo_listview
                        .getLayoutParams();
                linearParams.height = (int) (CommonUtil
                        .getWindowHeight(PhotoActivity.this) * 0.6);// 屏幕的高的60%
                select_photo_listview.setLayoutParams(linearParams);

                select_photo_gridview.setAdapter(photoAdapter);
                select_photo_listview.setAdapter(folderAdapter);
                select_photo_listview
                        .setOnItemClickListener(folderItemClickListener);
                select_photo_gridview
                        .setOnItemClickListener(photoItemClickListener);
            }
        }).execute();

    }


    private AdapterView.OnItemClickListener photoItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            String photoPath = null;
            if (position == 0) {
                goCamare();
            } else {
                photoPath = photoPathList.get(position);
                String start_str = "file://";
                String photo_path_str = photoPath.substring(start_str.length(),
                        photoPath.length());
                // 处理头像的代码
                CroperActivity.open(PhotoActivity.this,
                        photo_path_str);

            }
        }
    };


    private AdapterView.OnItemClickListener folderItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // photoPathList.clear();
            if (position != folderAdapter.getWhichFolder()) {
                String folderName = "";
                String folderPath = ((PhotoBean) folderAdapter.getItem(position)).getDirPath();
                if (folderPath != null) {
                    int lastIndexOf = folderPath.lastIndexOf("/");
                    folderName = folderPath.substring(lastIndexOf);
                }
                String strTitle = folderName.replace("/", "");
                if (strTitle.equals("Camera")) {
                    strTitle = "相机胶卷";
                }
                setAppTitle(strTitle);
                photoPathList = folderList.get(position).imagePaths;

                photoAdapter = new PhotoAdapter(PhotoActivity.this,
                        photoPathList);
                select_photo_gridview.setAdapter(photoAdapter);

                folderAdapter.setWhichFolder(position);
                folderAdapter.notifyDataSetChanged();
            }
            hideListAnimation();
        }
    };


    /**
     * 显示正在加载
     **/
    private void showLoading() {
        mPageState.showLoading();
        select_photo_gridview.setVisibility(View.GONE);
    }

    /**
     * 显示内容
     **/
    private void showContent() {
        mPageState.hide();
        select_photo_gridview.setVisibility(View.VISIBLE);
    }


    /**
     * 当前列表是否为空
     *
     * @return
     */
    private boolean isEmptyList() {
        return folderList.isEmpty() || folderList.size() == 0;
    }

    private void showListAnimation() {
        Animation animation = AnimationUtils.loadAnimation(this,
                R.anim.photo_folder_enter);
        // ta.setDuration(200);
        out_side_ll.startAnimation(animation);
        out_side_ll.setVisibility(View.VISIBLE);
    }

    private void hideListAnimation() {
        Animation animation = AnimationUtils.loadAnimation(this,
                R.anim.photo_folder_exit);
        // ta.setDuration(200);
        out_side_ll.startAnimation(animation);
        out_side_ll.setVisibility(View.GONE);
    }

    /**
     * 开启或关闭文件夹选项；
     *
     * @param isClickBack 是否按了返回键
     */
    private void openFolderChooser(boolean isClickBack) {
        if (isEmptyList()) {
            if (isClickBack) {
                finish();
            }
            return;
        }
        if (out_side_ll.getVisibility() == View.VISIBLE) {
            hideListAnimation();
        } else {
            if (isClickBack) {
                finish();
                overridePendingTransition(R.anim.slide_in_from_top,
                        R.anim.slide_out_to_bottom);
                return;
            }
            showListAnimation();
        }
    }


    /**
     * 得到系统图片并进行数据封装
     */
    private void getSystemPhotoData() {
        // 只查询jpeg和png的图片
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = contentResolver.query(mImageUri, null,
                MediaStore.Images.Media.MIME_TYPE + "=? or "
                        + MediaStore.Images.Media.MIME_TYPE + "=?",
                new String[]{"image/jpeg", "image/png"},
                MediaStore.Images.Media.DATE_MODIFIED);

        int _date = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
        // 遍历处理图片
        while (cursor.moveToNext()) {
            // 获取图片的路径
            String path = "file://" + cursor.getString(_date);
            File parentFile = new File(path).getParentFile();
            if (parentFile == null) {
                continue;
            }

            // 获取该图片的父路径名
            String dirPath = parentFile.getAbsolutePath();

            PhotoBean photoBean = null;
            if (!tempDir.containsKey(dirPath)) {
                photoBean = new PhotoBean();
                photoBean.setDirPath(dirPath);
                photoBean.setFirstImgPath(path);

                folderList.add(photoBean);
                tempDir.put(dirPath, folderList.indexOf(photoBean));
            } else {
                photoBean = folderList.get(tempDir.get(dirPath));
            }
            photoBean.imagePaths.add(path);
        }

        /** 图片倒叙 **/
        for (PhotoBean pb : folderList) {
            Collections.reverse(pb.imagePaths);
            pb.imagePaths.addFirst("drawable://" + R.mipmap.logo);
        }

        /**
         * 无任何照片的情况下能看到相机项
         */
        if (folderList.size() == 0) {
            folderList.add(new PhotoBean());
        }
        PhotoBean firstPhotoBean = null;
        if (folderList.size() > 1
                && !folderList.get(0).getDirPath().contains("/DCIM/Camera")) {

            for (PhotoBean photoBean : folderList) {
                if (photoBean.getDirPath().contains("/DCIM/Camera")) {
                    firstPhotoBean = photoBean;
                }

            }
            if (firstPhotoBean != null) {
                folderList.remove(firstPhotoBean);
                folderList.add(0, firstPhotoBean);
            }
        }

        cursor.close();
        tempDir = null;
    }


    /**
     * 使用相机拍照
     */
    protected void goCamare() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = getOutputMediaFileUri();
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    private String cameraPath;

    /**
     * 用于拍照时获取输出的Uri
     */
    protected Uri getOutputMediaFileUri() {
        cameraPath = BaseApp.getTempCache(getApplicationContext())
                + File.separator + System.currentTimeMillis() + ".jpg";
        return Uri.fromFile(new File(cameraPath));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && cameraPath != null) {
            // 处理头像的代码
            CroperActivity.open(PhotoActivity.this,
                    cameraPath);
        }
        return;
    }
}
